﻿// -----------------------------------------------------------------------
// <copyright file="ODataService.cs" company="None">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace ODataRegression.Framework.Core.MetaDataOM
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Web;
    using System.Net;
    using System.Xml.Linq;
    using AtomPayloadAnalyzer;
    using ODataRegression.Framework.Core.Shared;
    using ODataTestFrameworkCore.shared;


    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class ODataService
    {
        private string serviceURI;
        private List<ODataEntitySet> entitySetCollection;
        private XElement serviceMetadata;
       // public string hostName;
       // public string serviceName;
        public List<ODataEntitySet> EntitySetCollection { get { return this.entitySetCollection; } }
        public string ServiceURI { get { return this.ServiceURI; } }
        XElement ServiceMetadata { get { return this.serviceMetadata; } }

        ODataServiceInformation serviceInfo;
        private string GetServiceUrl(string serviceRoot)
        {
            string url = serviceRoot;
            //if (SvcFileName != string.Empty)
            //{
            //    url = serviceRoot + SvcFileName + "/";
            //}
            //else
            //{
            //    url = serviceRoot;
            //}
            if (!url.EndsWith("/"))
            {
                url = url + "/";
            }
            return url;
        }
        public ODataService(ODataServiceInformation serviceInfo)
        {

            serviceURI = serviceInfo.ServiceURI;
            //serviceName = svcName;

            this.serviceInfo = serviceInfo;
            this.serviceURI = GetServiceUrl(serviceURI);
            string MetadataURL = serviceURI + "$metadata";
            if (serviceURI.ToUpper().EndsWith(".SVC"))
            {
                MetadataURL = serviceURI + "/$metadata";
            }

            
            ODataTestResult getResult = HTTPHelpers.ExecuteGet(MetadataURL, false);
            
            if (getResult.expection == null)
            {
                using (XmlReader xrResponse = XmlReader.Create(getResult.webResp.GetResponseStream()))
                {
                    this.serviceMetadata = XElement.Load(xrResponse);

                }

                getResult.webResp.Close();

                getResult = null;
                getResult = HTTPHelpers.ExecuteGet(serviceURI, false);
                if (getResult.expection == null)
                {
                    using (XmlReader xrResponse = XmlReader.Create(getResult.webResp.GetResponseStream()))
                    {
                        entitySetCollection = GetEntityCollection(xrResponse);
                    }

                    getResult.webResp.Close();
                }
                else
                {
                    throw getResult.expection;
                }

               
            }
            else
            {
                throw getResult.expection;
            }
            
            
        }

        private List<ODataEntitySet> GetEntityCollection(XmlReader xrResponseServiceRoot)
        {
            List<ODataEntitySet> entitySetCollection = new List<ODataEntitySet>();
            XElement serviceWorkSpace = XElement.Load(xrResponseServiceRoot);

            XElement nodes = serviceWorkSpace.Elements(ODataNameSpaces.AppNamespace + ODataElementTypes.workspace.ToString()).First();
            string href=string.Empty;
            foreach (XElement collectionRef in nodes.Elements(ODataNameSpaces.AppNamespace + ODataElementTypes.collection.ToString()))
            {
                if (collectionRef.Name.LocalName == ODataElementTypes.collection.ToString())
                {
                    href=collectionRef.Attribute(ODataAttributeTypes.href.ToString()).Value;
                    string collectionUrl = serviceURI + href;

                    entitySetCollection.Add(new ODataEntitySet(this.serviceInfo.ServiceBusinessName, collectionUrl, href, this.serviceMetadata));
                }
            }

            return entitySetCollection;
        }

        private List<ODataServiceOperation> GetServiceOperationCollection()
        {
            throw new NotImplementedException();
        }
    }
}
